package cn.edu.scau.cmi.wuzhenzhou.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import cn.edu.scau.cmi.wuzhenzhou.composite.safe.SafeOrganization;
import cn.edu.scau.cmi.wuzhenzhou.composite.safe.SafePerson;
import cn.edu.scau.cmi.wuzhenzhou.composite.safe.SafeTeam;

public class SafeCompositeClient {

	public void start() {
		Scanner input = new Scanner(System.in);
		String op = null;
		int num;

		System.out.println("安全组合模式");
		SafeTeam root = new SafeTeam();
		System.out.println("请输入组织名字:");
		op = input.next();
		root.setName(op);
		while (true) {
			System.out.println("输入你要进行的操作: 1、增加团队 2、增加人员 3、删除团队或人员  4、展示所有 5、退出");
			op = input.next();
			switch (op) {
			case "1": {
				System.out.print("输入新增团队名字：");
				op = input.next();
				SafeTeam team = new SafeTeam();
				team.setName(op);
				root.getChildren().add(team);
				break;
			}
			case "2": {
				int i;
				System.out.println("选择人员加入团队：");
				for (i = 0; i < root.getChildren().size(); i++) {
					System.out.print(i+1 + "." + root.getChildren().get(i).getName() + "  ");
				}
				System.out.println();
				num = input.nextInt()-1;
				System.out.print("输入人员名字：");
				op = input.next();
				SafePerson person = new SafePerson();
				person.setName(op);
				((SafeTeam)(root.getChildren().get(num))).addChild(person);
				break;
			}
			case "3": {
				System.out.print("输入删除对象的名字：");
				op = input.next();
				delete(root, op);
				break;
			}
			case "4": {
				System.out.println(root.getName());
				display(root);
				break;
			}
			default: {
				return;
			}
			}
			System.out.println();
		}

	}

	static void display(SafeTeam root) {
		List<SafeOrganization> children = root.getChildren();

		for (SafeOrganization c : children) {
			if (c instanceof SafePerson) {
				System.out.print("\t\t");
				System.out.println("-" + c.getName());
			} else {
				System.out.print("\t");
				System.out.println("-" + c.getName());
				display((SafeTeam)c);
			}
		}
	}
	
	static void delete(SafeTeam root, String name) {
		List<SafeOrganization> children = root.getChildren();

		for (SafeOrganization c : children) {
			if(c.getName().equals(name)) {
				root.deleteChild(name);
				return;
			}
			if (c instanceof SafeTeam) {
				delete((SafeTeam)c, name);
			}
		}
	}
}